package com.xbongbong.paas.help;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.SerialDateEnum;
import com.xbongbong.paas.enums.VisibleTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.SerialNumberPoJo;
import com.xbongbong.paas.field.VisibleRulePoJo;
import com.xbongbong.paas.field.VisibleRuleVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.abstracts.AbstractFormExplainHandleName;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.SetTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.dictionary.DictionarySpecialEnum;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.RoleEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.help.PackageHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: wufeng
 * @date: 2018/10/31 17:50
 * @desrcption: 用于回显字段数据
 */
@Component
public class FormDesignFormExplainHandleName extends AbstractFormExplainHandleName {
    private static final Logger LOG = LoggerFactory.getLogger(FormDesignFormExplainHandleName.class);

    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private PackageHelp packageHelp;

    /**
     * 处理字段中的部门，角色，用户的名称
     * @return
     * @throws XbbException
     */
    @Override
    public HandlerExplainVO handleExplain(HandlerExplainDTO handlerExplainDTO) throws XbbException{
        HandlerExplainVO handlerExplainVO = new HandlerExplainVO();
        try {
            PaasFormEntityExt paasFormEntityExt = handlerExplainDTO.getPaasFormEntityExt();
            List<FieldAttrEntity> explainList = handlerExplainDTO.getExplainList();
            List<FieldAttrEntity> list = new ArrayList<>();
            //用户集合
            Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            //部门集合
            Map<String, DepartmentEntity> departmentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            //角色集合
            Map<String, RoleEntity> roleMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            List<String> featureList = packageHelp.getFeatureList(handlerExplainDTO.getCorpid());
            for (FieldAttrEntity entity: explainList) {
                setDefaultAndRule(entity, handlerExplainDTO, userMap, departmentMap, roleMap, featureList);
                if (Objects.equals(handlerExplainDTO.getBusinessType(), XbbRefTypeEnum.COMMUNICATE_PLAN.getCode()) && Objects.equals(entity.getAttr(), CommunicatePlanEnum.TARGET.getAttr())) {
                    entity.setSetType(3);
                }
                //销售机会开放输单备注勾选，张天瑞要求
                if (Objects.equals(handlerExplainDTO.getBusinessType(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode()) && Objects.equals(entity.getAttr(), SalesOpportunityEnum.WASTAGE_MEMO.getAttr())) {
                    entity.setSetType(SetTypeEnum.DISABLE_REPEAT.getCode());
                }
                entity.setItems(proFormHelp.setItemAndComboItems(entity, paasFormEntityExt));
                if (Objects.equals(entity.getFieldType(),FieldTypeEnum.SELECT_PRODUCT.getType())){
                    proFormHelp.setProductAccuracy(entity,handlerExplainDTO.getCorpid(), handlerExplainDTO.getUserId());
                }
                if (Objects.equals(entity.getFieldType(),FieldTypeEnum.LABEL.getType())){
                    proFormHelp.setLabelDefaultValue(entity, handlerExplainDTO.getCorpid());
                }
                if (ExplainUtil.isSubForm(entity.getFieldType()) && Objects.nonNull(entity.getSubForm())) {
                    List<? extends FieldAttrEntity> subFieldList = entity.getSubForm().getItems();
                    if (Objects.nonNull(subFieldList)) {
                        Iterator<? extends FieldAttrEntity> iterator = subFieldList.iterator();
                        while (iterator.hasNext()) {
                            FieldAttrEntity subField = iterator.next();
                            setDefaultAndRule(subField, handlerExplainDTO, userMap, departmentMap, roleMap, featureList);
                        }
                    }
                }
                entity.setIsDictionary(setIsDictionary(entity, XbbRefTypeEnum.transferBusinessType4Distributor(paasFormEntityExt.getBusinessType(), paasFormEntityExt.getDistributorMark())));
                // 天瑞新需求，产品表单的产品名称不允许重复值打开
                if (Objects.equals(handlerExplainDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())&&Objects.equals(entity.getAttr(), ProductEnum.NAME.getAttr())){
                    entity.setSetType(SetTypeEnum.DISABLE_OPEN.getCode());
                }
                list.add(entity);
            }
            handlerExplainVO.setHeadList(list);
            handleExplainDefaultLimit(handlerExplainVO, handlerExplainDTO);
        } catch (Exception e){
            LOG.error("处理字段中的部门、角色、用户等名称报错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return handlerExplainVO;
    }

    /**
     * 设置默认值和高级可见，可编辑，可新建，可删除中的用户、部门、角色
     * @param entity
     * @param handlerExplainDTO
     * @param userMap
     * @param departmentMap
     * @param roleMap
     * @throws XbbException
     */
    private void setDefaultAndRule(FieldAttrEntity entity, HandlerExplainDTO handlerExplainDTO, Map<String, UserEntity> userMap,
                             Map<String, DepartmentEntity> departmentMap, Map<String, RoleEntity> roleMap, List<String> featureList) throws XbbException {
        // 【高级/旗舰->标准】（子表单，关联数据，成员单选，成员多选，部门多选，部门单选）表单设置隐藏掉
        packageHelp.explainDesignHide(featureList, entity);
        if (Objects.nonNull(entity.getDefaultAttr()) && CollectionsUtil.isNotEmpty(entity.getDefaultAttr().getDefaultList())) {
            List<OptionalRangeEntity> defaultList = entity.getDefaultAttr().getDefaultList();
            defaultList = formDataFormExplainHelper.handleOptionalRangeList(defaultList, handlerExplainDTO.getCorpid(), userMap, departmentMap, roleMap);
            entity.getDefaultAttr().setDefaultList(defaultList);
        }
        // 流水号默认值修改(针对历史表单)dateFormat 为none 的值
        if (Objects.equals(entity.getAttr(),FieldTypeEnum.SERIALNO.getAlias())){
            SerialNumberPoJo serialNumber = entity.getSerialNumber();
            if (Objects.nonNull(serialNumber) && Objects.equals(serialNumber.getDateFormat(), SerialDateEnum.NONE.getValue())){
                serialNumber.setResetCycle(BasicConstant.ZERO);
            }
        }
        // 高级可见
        setVisibleRuleName(entity.getVisibleScopeRule(), entity.getVisibleScopeEnable(), handlerExplainDTO, userMap, departmentMap, roleMap);
        // 高级可见、高级编辑为null时，初始化一下
        setNullAdvancedRule(entity);
        // 高级编辑
        setVisibleRuleName(entity.getEditableRule(), entity.getEditableAdvanceEnable(), handlerExplainDTO, userMap, departmentMap, roleMap);
        // 新增高级设置规则
        setVisibleRuleName(entity.getAddRule(), entity.getAddAdvanceEnable(), handlerExplainDTO, userMap, departmentMap, roleMap);
        // 删除高级设置规则
        setVisibleRuleName(entity.getRemoveRule(), entity.getRemoveAdvanceEnable(), handlerExplainDTO, userMap, departmentMap, roleMap);
    }

    /**
     * 往高级规则的属性里塞名字
     * @param visibleRulePoJo
     * @param handlerExplainDTO
     * @param userMap
     * @param departmentMap
     * @param roleMap
     * @throws XbbException
     */
    private void setVisibleRuleName(VisibleRulePoJo visibleRulePoJo, Integer enable,  HandlerExplainDTO handlerExplainDTO, Map<String, UserEntity> userMap,
                         Map<String, DepartmentEntity> departmentMap, Map<String, RoleEntity> roleMap) throws XbbException {
        if(visibleRulePoJo != null && Objects.equals(enable, 1)){
            List<VisibleRuleVO> userVoList = new ArrayList<>();
            List<String> users = visibleRulePoJo.getUser();
            List<String> userResult = new ArrayList<>();
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(StringConstant.CORPID, handlerExplainDTO.getCorpid());
            param.put(StringConstant.DEL, handlerExplainDTO.getDel());
            formDataFormExplainHelper.getUserMap(userMap, param);
            for(String userId: users){
                VisibleRuleVO userVO = new VisibleRuleVO();
                userVO.setId(userId);
                if(userMap.containsKey(userId)){
                    userResult.add(userId);
                }
                UserEntity userEntity = formDataFormExplainHelper.getUserName(userId, userMap);
                if(userEntity != null){
                    userVO.setName(userEntity.getName());
                }
                userVO.setUserId(userId);
                userVoList.add(userVO);
            }
            visibleRulePoJo.setUserList(userVoList);
            visibleRulePoJo.setUser(userResult);
            List<VisibleRuleVO> dept = visibleRulePoJo.getDep();
            List<VisibleRuleVO> deptResult = new ArrayList<>();
            param.clear();
            param.put(StringConstant.CORPID, handlerExplainDTO.getCorpid());
            param.put(StringConstant.DEL, handlerExplainDTO.getDel());
            formDataFormExplainHelper.getDepartmentMap(departmentMap, param);
            for (VisibleRuleVO deptId: dept){
                if(departmentMap.containsKey(deptId.getId().toString())){
                    deptResult.add(deptId);
                }
            }
            visibleRulePoJo.setDep(deptResult);
            List<Integer> role = visibleRulePoJo.getRole();
            List<Integer> roleResult = new ArrayList<>();
            param.clear();
            param.put(StringConstant.CORPID, handlerExplainDTO.getCorpid());
            param.put(StringConstant.DEL, handlerExplainDTO.getDel());
            formDataFormExplainHelper.getRoleMap(roleMap, param);
            for(Integer roleId: role){
                if(roleMap.containsKey(roleId.toString())){
                    roleResult.add(roleId);
                }
            }
            visibleRulePoJo.setRole(roleResult);
        }

    }

    /**
     * 将高级可见规则、高级编辑规则为null时，赋初始值
     * @param entity
     */
    private static void  setNullAdvancedRule(FieldAttrEntity entity) {
        boolean editHide = Objects.isNull(entity.getEditHide()) || Objects.equals(0, entity.getEditHide());
        VisibleRulePoJo visibleRulePoJo = entity.getVisibleScopeRule();
        // 高级可见规则
        if (Objects.isNull(visibleRulePoJo) && editHide) {
            // 显示在界面上，且高级可见为null，赋初始值
            entity.setVisibleScopeEnable(0);
            visibleRulePoJo = new VisibleRulePoJo();
            visibleRulePoJo.setType(VisibleTypeEnum.NOT_SHOW_ANYONE.getType());
            entity.setVisibleScopeRule(visibleRulePoJo);
        }
        // 高级编辑规则
        VisibleRulePoJo editableRule = entity.getEditableRule();
        boolean edit = Objects.equals(entity.getShowEditable(), 1);
        if (Objects.isNull(editableRule) && edit) {
            // 高级编辑显示在界面上，且高级编辑属性为null，赋初始值
            entity.setEditableAdvanceEnable(0);
            editableRule = new VisibleRulePoJo();
            editableRule.setType(VisibleTypeEnum.SOME_PEOPLE_CAN_SEE.getType());
            entity.setEditableRule(editableRule);
        }
    }
    /**
     * 是否特殊的数据字典
     * @param fieldAttrEntity
     * @param businessType
     * @return
     * 创建时间 2019/6/13 2:43 PM
     * 修改时间 2019/6/13 2:43 PM
     * @author chy
     * @since v1.0
     * @version v1.0
     */
    private Integer setIsDictionary(FieldAttrEntity fieldAttrEntity, Integer businessType){
        DictionarySpecialEnum dictionarySpecialEnum = DictionarySpecialEnum.getEnum(businessType, fieldAttrEntity.getSaasAttr());
        if (dictionarySpecialEnum == DictionarySpecialEnum.UNKNOWN) {
            return BasicConstant.ZERO;
        }
        return BasicConstant.ONE;
    }
}
